/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

// import * as nls from 'vscode-nls';
// const localize = nls.loadMessageBundle();

import { LanguageClient, TransportKind } from 'vscode-languageclient';
import { CompletionRequest, HoverRequest, DocumentSymbolRequest, DefinitionRequest, DocumentHighlightRequest, ReferencesRequest, CodeActionRequest, RenameRequest } from 'vscode-languageserver-protocol';
import * as vsProto from 'vscode-languageserver-protocol';
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageService, Stylesheet } from 'vscode-css-languageservice';
import * as vsclient from 'vscode-languageclient';
interface LanguageModelCache<T> {
	get(document: any): T;
	onDocumentRemoved(document: any): void;
	dispose(): void;
}
function formatError(message: string, err: any): string {
	if (err instanceof Error) {
		let error = <Error>err;
		return `${message}: ${error.message}\n${error.stack}`;
	} else if (typeof err === 'string') {
		return `${message}: ${err}`;
	} else if (err) {
		return `${message}: ${err.toString()}`;
	}
	return message;
}

function runSafe<T>(func: () => Thenable<T> | T, errorVal: T, errorMessage: string, detail: any): Thenable<T> | T {
	try {
		let t = func();
		if (t instanceof Promise) {
			return t.then((v) => {
				detail.resolver(v);
				return void 0;
			}, e => {
				detail.rejecter(formatError(errorMessage, e));
				console.error(formatError(errorMessage, e));
				return errorVal;
			});
		}
		detail.resolver(t);
		return t;
	} catch (e) {
		console.error(formatError(errorMessage, e));
		return errorVal;
	}
}
function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: any) => T): LanguageModelCache<T> {
	let languageModels: { [uri: string]: { version: number, languageId: string, cTime: number, languageModel: T } } = {};
	let nModels = 0;

	let cleanupInterval = 0;
	if (cleanupIntervalTimeInSec > 0) {
		cleanupInterval = setInterval(() => {
			let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
			let uris = Object.keys(languageModels);
			for (let uri of uris) {
				let languageModelInfo = languageModels[uri];
				if (languageModelInfo.cTime < cutoffTime) {
					delete languageModels[uri];
					nModels--;
				}
			}
		}, cleanupIntervalTimeInSec * 1000);
	}

	return {
		get(document: any): T {
			let version = document.version;
			let languageId = document.languageId;
			let languageModelInfo = languageModels[document.uri];
			if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
				languageModelInfo.cTime = Date.now();
				return languageModelInfo.languageModel;
			}
			let languageModel = parse(document);
			languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
			if (!languageModelInfo) {
				nModels++;
			}

			if (nModels === maxEntries) {
				let oldestTime = Number.MAX_VALUE;
				let oldestUri = null;
				for (let uri in languageModels) {
					let languageModelInfo = languageModels[uri];
					if (languageModelInfo.cTime < oldestTime) {
						oldestUri = uri;
						oldestTime = languageModelInfo.cTime;
					}
				}
				if (oldestUri) {
					delete languageModels[oldestUri];
					nModels--;
				}
			}
			return languageModel;

		},
		onDocumentRemoved(document: any) {
			let uri = document.uri;
			if (languageModels[uri]) {
				delete languageModels[uri];
				nModels--;
			}
		},
		dispose() {
			if (typeof cleanupInterval !== 'undefined') {
				clearInterval(cleanupInterval);
				cleanupInterval = void 0;
				languageModels = {};
				nModels = 0;
			}
		}
	};
}
var vscode;
function initVsCode() {
	vscode = vscode || (vscode = window["getVsCode"]("css"));
}

function asPosition(value) {
	if (!value) {
		return undefined;
	}
	return new vscode.Position(value.line, value.character);
}
function asRange(value) {
	if (!value) {
		return undefined;
	}
	return new vscode.Range(asPosition(value.start), asPosition(value.end));
}
// this method is called when vs code is activated
export function activate(context: any) {
	initVsCode();
	var documents = new Map<any, any>();
	vscode.workspace.textDocuments.forEach(doc => {
		documents.set(doc.uri.toString(), doc);
	});
	let stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
	vscode.workspace.onDidCloseTextDocument(doc => {
		stylesheets.onDocumentRemoved(doc);
		documents.delete(doc.uri.toString());
	});
	vscode.workspace.onDidOpenTextDocument(doc => {
		documents.set(doc.uri.toString(), doc);
	});
	let languageServices: { [id: string]: LanguageService } = {
		css: getCSSLanguageService(),
		scss: getSCSSLanguageService(),
		less: getLESSLanguageService()
	};

	function getLanguageService(document: any) {
		let service = languageServices[document.languageId];
		if (!service) {
			console.log('Document type is ' + document.languageId + ', using css instead.');
			service = languageServices['css'];
		}
		return service;
	}
	// The server is implemented in node
	let serverModule = context.asAbsolutePath("");
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=6044'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};
	let documentSelector = ['css', 'scss', 'less'];

	// Options to control the language client
	let clientOptions = {
		documentSelector,
		synchronize: {
			configurationSection: ['css', 'scss', 'less']
		},
		initializationOptions: {
		},
		vscode: vscode
	};

	//let scopedSettingsSupport = false;
	window.addEventListener("css_request_initialize", (ev: CustomEvent) => {
		var detail = ev.detail.params;
		function hasClientCapability(name: string) {
			let keys = name.split('.');
			let c: any = detail.capabilities;
			for (let i = 0; c && i < keys.length; i++) {
				c = c[keys[i]];
			}
			return !!c;
		}
		let snippetSupport = hasClientCapability('textDocument.completion.completionItem.snippetSupport');
		//scopedSettingsSupport = hasClientCapability('workspace.configuration');
		let capabilities = {
			// Tell the client that the server works in FULL text document sync mode
			textDocumentSync: 1,//documents.syncKind,
			completionProvider: snippetSupport ? { resolveProvider: false } : undefined,
			hoverProvider: true,
			documentSymbolProvider: true,
			referencesProvider: true,
			definitionProvider: true,
			documentHighlightProvider: true,
			codeActionProvider: true,
			renameProvider: true,
			colorProvider: true
		};
		var cb = ev.detail["requests"].get("css_request_initialize_" + ev.detail.uuid);
		cb && cb({ capabilities });
	});
	// Create the language client and start the client.
	let client = new LanguageClient('css', 'CSS Language Server', serverOptions, clientOptions);
	client.registerFeature(new (<any>vsclient).ConfigurationFeature(client));

	let disposable = client.start();
	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);

	// client.onReady().then(_ => {
	// 	// register color provider
	// 	context.subscriptions.push(vscode.languages.registerColorProvider(documentSelector, {
	// 		provideDocumentColors(document: any): Thenable<any[]> {
	// 			let params = {
	// 				textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
	// 			};
	// 			return client.sendRequest((<any>vsProto).DocumentColorRequest.type.method, params).then((symbols: any) => {
	// 				return symbols.map(symbol => {
	// 					let range = client.protocol2CodeConverter.asRange(symbol.range);
	// 					let color = new vscode.Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
	// 					return new vscode.ColorInformation(range, color);
	// 				});
	// 			});
	// 		},
	// 		provideColorPresentations(color: any, context): any[] | Thenable<any[]> {
	// 			let params = {
	// 				textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),
	// 				color,
	// 				range: client.code2ProtocolConverter.asRange(context.range)
	// 			};
	// 			return client.sendRequest((<any>vsProto).ColorPresentationRequest.type.method, params).then((presentations: any) => {
	// 				return presentations.map(p => {
	// 					let presentation = new vscode.ColorPresentation(p.label);
	// 					presentation.textEdit = p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit);
	// 					presentation.additionalTextEdits = p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
	// 					return presentation;
	// 				});
	// 			});
	// 		}
	// 	}));
	// });

	let indentationRules = {
		increaseIndentPattern: /(^.*\{[^}]*$)/,
		decreaseIndentPattern: /^\s*\}/
	};

	vscode.languages.setLanguageConfiguration('css', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	vscode.languages.setLanguageConfiguration('less', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	vscode.languages.setLanguageConfiguration('scss', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g,
		indentationRules: indentationRules
	});

	const regionCompletionRegExpr = /^(\s*)(\/(\*\s*(#\w*)?)?)?$/;
	vscode.languages.registerCompletionItemProvider(documentSelector, {
		provideCompletionItems(doc, pos) {
			let lineUntilPos = doc.getText(new vscode.Range(new vscode.Position(pos.line, 0), pos));
			let match = lineUntilPos.match(regionCompletionRegExpr);
			if (match) {
				let range = new vscode.Range(new vscode.Position(pos.line, match[1].length), pos);
				let beginProposal = new vscode.CompletionItem('#region', vscode.CompletionItemKind.Snippet);
				beginProposal.range = range; vscode.TextEdit.replace(range, '/* #region */');
				beginProposal.insertText = new vscode.SnippetString('/* #region $1*/');
				beginProposal.documentation = 'Folding Region Start';
				beginProposal.filterText = match[2];
				beginProposal.sortText = 'za';
				let endProposal = new vscode.CompletionItem('#endregion', vscode.CompletionItemKind.Snippet);
				endProposal.range = range;
				endProposal.insertText = '/* #endregion */';
				endProposal.documentation = 'Folding Region End';
				endProposal.sortText = 'zb';
				endProposal.filterText = match[2];
				return [beginProposal, endProposal];
			}
			return null;
		}
	});

	window.addEventListener("css_request_" + CompletionRequest.type.method, (ev: CustomEvent) => {
		var textDocumentPosition = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(textDocumentPosition.textDocument.uri.toString());
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).doComplete(document, textDocumentPosition.position, stylesheet)!; /* TODO: remove ! once LS has null annotations */
		}, null, `在为 ${textDocumentPosition.textDocument.uri} 执行智能提示时发生错误`, ev.detail);
	});
	window.addEventListener("css_request_" + HoverRequest.type.method, (ev: CustomEvent) => {
		var textDocumentPosition = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(textDocumentPosition.textDocument.uri);
			let styleSheet = stylesheets.get(document);
			return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet)!; /* TODO: remove ! once LS has null annotations */
		}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, ev.detail);
	});
	window.addEventListener("css_request_" + DocumentSymbolRequest.type.method, (ev: CustomEvent) => {
		var documentSymbolParams = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(documentSymbolParams.textDocument.uri);
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).findDocumentSymbols(document, stylesheet);
		}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, ev.detail);
	});
	window.addEventListener("css_request_" + DefinitionRequest.type.method, (ev: CustomEvent) => {
		var documentSymbolParams = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(documentSymbolParams.textDocument.uri);
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).findDefinition(document, documentSymbolParams.position, stylesheet);
		}, null, `Error while computing definitions for ${documentSymbolParams.textDocument.uri}`, ev.detail);
	});

	window.addEventListener("css_equest_" + DocumentHighlightRequest.type.method, (ev: CustomEvent) => {
		var documentSymbolParams = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(documentSymbolParams.textDocument.uri);
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).findDocumentHighlights(document, documentSymbolParams.position, stylesheet);
		}, [], `Error while computing document highlights for ${documentSymbolParams.textDocument.uri}`, ev.detail);
	});
	window.addEventListener("css_request_" + ReferencesRequest.type.method, (ev: CustomEvent) => {
		var referenceParams = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(referenceParams.textDocument.uri);
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
		}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, ev.detail);
	});
	window.addEventListener("css_request_" + CodeActionRequest.type.method, (ev: CustomEvent) => {
		var codeActionParams = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(codeActionParams.textDocument.uri);
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
		}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, ev.detail);
	});
	window.addEventListener("css_request_" + (<any>vsProto).ColorPresentationRequest.type.method, (ev: CustomEvent) => {
		var params = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(params.textDocument.uri);
			if (document) {
				let stylesheet = stylesheets.get(document);
				return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
			}
			return [];
		}, [], `Error while computing color presentations for ${params.textDocument.uri}`, ev.detail);
	});
	window.addEventListener("css_request_" + RenameRequest.type.method, (ev: CustomEvent) => {
		var renameParameters = ev.detail.params[0];
		runSafe(() => {
			let document = documents.get(renameParameters.textDocument.uri);
			let stylesheet = stylesheets.get(document);
			return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
		}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, ev.detail);
	});

	window.addEventListener("css_request_" + (<any>vsProto).DocumentColorRequest.type.method, (ev: CustomEvent) => {
		var params = ev.detail.params[0];
		return runSafe(() => {
			let document = documents.get(params.textDocument.uri);
			if (document) {
				let stylesheet = stylesheets.get(document);
				return getLanguageService(document).findDocumentColors(document, stylesheet);
			}
			return [];
		}, [], `Error while computing document colors for ${params.textDocument.uri}`, ev.detail);
	});
	vscode.commands.registerCommand('_css.applyCodeAction', applyCodeAction);

	function applyCodeAction(uri: string, documentVersion: number, edits: any[]) {
		let textEditor = vscode.window.activeTextEditor;
		if (textEditor && textEditor.document.uri.toString() === uri) {
			if (textEditor.document.version !== documentVersion) {
				vscode.window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`);
			}
			textEditor.edit(mutator => {
				for (let edit of edits) {
					mutator.replace(asRange(edit.range), edit.newText);
				}
			}).then(success => {
				if (!success) {
					vscode.window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.');
				}
			});
		}
	}
}

